package com.hong.chapter10;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Optional;

public class BooleanLock implements  LOCK {
    //标识
    private boolean initValue;

    private Collection<Thread> blockedThreadCollection = new ArrayList<>();

    private static Thread currentThread;

    //The initValue
    public BooleanLock() {
        this.initValue = false;
    }




    @Override
    public synchronized void lock() throws InterruptedException {
        while (initValue){
            currentThread=Thread.currentThread();
            blockedThreadCollection.add(Thread.currentThread());
            this.wait();
        }
        blockedThreadCollection.remove(Thread.currentThread());
        this.initValue=true;
    }

    @Override
    public synchronized void lock(long mills) throws InterruptedException, TimeOutException {
        if(mills<=0){
            lock();
        }
        long hasRemaining = mills;
        long endTime = System.currentTimeMillis()+mills;
        while (initValue){
            if(hasRemaining<=0){
                throw new TimeOutException("Time out");
            }
            blockedThreadCollection.add(Thread.currentThread());
            this.wait(mills);
            hasRemaining=System.currentTimeMillis()-endTime;
            System.out.println(Thread.currentThread().getName()+">>"+hasRemaining);
        }
        this.initValue = true;
        this.currentThread=Thread.currentThread();
    }

    @Override
    public synchronized void unlock() {
        if(Thread.currentThread() == currentThread){
            this.initValue = false;
            Optional.of(Thread.currentThread().getName()+" release the lock monitor.")
                    .ifPresent(System.out::println);
            this.notifyAll();
        }

    }

    @Override
    public Collection<Thread> getBlockedThread() {
        return Collections.unmodifiableCollection(blockedThreadCollection);
    }

    @Override
    public int getBlockedSize() {
        return 0;
    }
}
